from os import access

from tortoise.functions import Sum

from app.controllers.customer.share import share_controller
from app.controllers.marketing.coupons import coupons_controller
from app.controllers.orders.wechat import wechat_controller
from app.controllers.saas.cases import cases_controller
from app.controllers.saas.consumables import consumables_controller
from app.controllers.saas.consumables_use import consumables_use_controller
from app.core.ctx import CTX_USER_ID
from app.models import CustomerUser, OrdersReceive, Cases, ConsumablesUse, Consumables
from app.settings import settings
from fastapi import APIRouter, HTTPException, UploadFile, Query
from tortoise.expressions import Q
from app.controllers.customer.users import users_controller
from app.schemas import Success, SuccessExtra, Fail
from app.schemas.customer import *
from app.utils.upload import upload_image
from app.core.dependency import DependCustomerAuth
import httpx

mini_users_router = APIRouter()
app_id = settings.WEICHAT_APP_ID
app_secret = settings.WEICHAT_APP_SECRET


@mini_users_router.post("/access_token", summary="获取token")
async def login_access_token(credentials: CredentialsSchema):
    data = await users_controller.get_token(credentials)
    return Success(data=data)


@mini_users_router.get("/userinfo", summary="查看用户信息", dependencies=[DependCustomerAuth])
async def get_userinfo(
        customer_id: int = Query(0, description="页码"),
):
    user_id = CTX_USER_ID.get()
    user_obj = await users_controller.get(id=user_id)
    if customer_id:
        user_id = customer_id
    coupons_count, data = await coupons_controller.get_user_coupons(user_id)
    data = await user_obj.to_dict(exclude_fields=["password"])
    data['coupons_count'] = coupons_count
    if data['birth']:
        birth = datetime.fromisoformat(data['birth'].replace("Z", "+00:00"))
        data['birth'] = birth.strftime("%Y-%m-%d")
    return Success(data=data)


@mini_users_router.get("/user_photo", summary="查看用户对比照", dependencies=[DependCustomerAuth])
async def get_user_photo(
        customer_id: int = Query(0, description="用户id"),
):
    user_id = CTX_USER_ID.get()
    if customer_id:
        user_id = customer_id
    case_obj = await Cases.filter(user_id=user_id).filter(
        Q(before_pic__isnull=False) | Q(after_pic__isnull=False)).values("id", "before_pic", "after_pic")

    return Success(data=case_obj)


@mini_users_router.get("/user_consumable", summary="查看用户耗材", dependencies=[DependCustomerAuth])
async def get_user_consumable(
        customer_id: int = Query(0, description="用户id"),
):
    user_id = CTX_USER_ID.get()
    if customer_id:
        user_id = customer_id
    consumable_obj = await ConsumablesUse.filter(user_id=user_id).order_by('consumables_id').values('consumables_id')

    for consumable in consumable_obj:
        consumable_data = await Consumables.get(id=consumable['consumables_id'])
        consumable['name'] = consumable_data.name
        consumable['guige'] = consumable_data.guige
        consumable['danwei'] = consumable_data.danwei
        consumable['type'] = consumable_data.type

    return Success(data=consumable_obj)


@mini_users_router.post("/create", summary="创建新用户")
async def create_customer(
        user_in: CustomerUserCreate,
):
    await users_controller.create_user(obj_in=user_in)
    return Success(msg="创建新会员成功")


@mini_users_router.post("/usermod", summary="修改用户信息", dependencies=[DependCustomerAuth])
async def get_usermod(
        data_in: CustomerMod,
):
    user_id = CTX_USER_ID.get()

    if user_id == 1:
        return Success()
    if data_in.id == 0 or data_in.id is None:
        data_in.id = user_id

    parent = await CustomerUser.filter(phone=data_in.friend_phone).first()
    if parent:
        data_in.parent_id = parent.id
    else:
        data_in.parent_id = 1
    await users_controller.update(id=data_in.id, obj_in=data_in)

    await OrdersReceive.update_or_create(
        user_id=data_in.id,
        receive_name=data_in.name,
        receive_phone=data_in.phone,
        receive_address=data_in.address
    )

    return Success()


@mini_users_router.get("/wechat_get_phone", summary="获取手机号")
async def do_wechat_get_phone(js_code: str):
    access_token = await wechat_controller.get_access_token()
    # 1. 使用 code 获取 access token
    token_url = f"https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={access_token}"
    async with httpx.AsyncClient() as client:
        response = await client.post(token_url, json={"code": js_code})
        data = response.json()
    # 2. 检查返回数据
    if data['errcode'] > 0:
        raise HTTPException(status_code=400, detail=data["errmsg"])
    data_phone = data["phone_info"]
    phone = data_phone["phoneNumber"]
    #注册或者登录
    return Success(data=data_phone)


@mini_users_router.post("/wechat_openid", summary="微信获取openid")
async def do_wechat_openid(weichatopenid: CustomerWeichatOpenid):
    # 1. 使用 code 获取 session_key 和 openid
    url = (
        f"https://api.weixin.qq.com/sns/jscode2session?"
        f"appid={app_id}&secret={app_secret}&js_code={weichatopenid.code}&grant_type=authorization_code"
    )
    async with httpx.AsyncClient() as client:
        response = await client.get(url)
        data = response.json()
        print("data", data)

    if "errcode" in data:
        raise HTTPException(status_code=400, detail=data["errmsg"])
    session_key = data["session_key"]
    openid = data["openid"]
    # 2. 解密用户微信信息
    user_info = await users_controller.decrypt_user_phone(weichatopenid.encryptedData, session_key, weichatopenid.iv)
    # 3. 这里可以根据 openid 和 phone_number 登录或注册用户
    return Success(data=user_info)


@mini_users_router.post("/wechat_login", summary="微信登录/注册")
async def do_wechat_login(weichatlogin: CustomerWeichatLogin):
    data = await users_controller.mini_login(weichatlogin=weichatlogin)
    return Success(data=data)


@mini_users_router.post("/file", summary="上传头像")
async def file_customer(file: UploadFile):
    url = await upload_image(file, "customer")
    if not url:
        return Fail(code=400, msg="图片格式错误")
    data = {"url": url}
    return Success(data=data)


@mini_users_router.post("/share", summary="用户分享", dependencies=[DependCustomerAuth])
async def customer_share(
        data_in: CustomerShareCreate,
):
    user_id = CTX_USER_ID.get()
    data_in.user_id = user_id
    await share_controller.do_create(obj_in=data_in)

    return Success(msg="创建成功")


@mini_users_router.get("/my_visit", summary="我的邀请", dependencies=[DependCustomerAuth])
async def customer_visit(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
):
    user_id = CTX_USER_ID.get()
    total, data = await users_controller.get_visit(page=page, page_size=page_size, user_id=user_id)

    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)
